package com.happle.gcmclient;

import java.util.ArrayList;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.happle.gcmclient.config.CommonUtilities;
import com.happle.gcmclient.config.Constants;
import com.happle.gcmclient.config.GlobalValue;
import com.happle.gcmclient.managers.MessagesManager;
import com.happle.gcmclient.obj.MessageObj;

public class MessageActivity extends BaseActivity {

	private final String TAG = this.getClass().getSimpleName();
	// UI vars
	private TextView tvMessage;
	private EditText txtMessage;
	private Button btnSend;

	private MessagesManager messageManager;
	private ArrayList<MessageObj> listMessages;
	private ArrayAdapter<MessageObj> messageAdapter;
	private static Activity self;

	private ListView lvConversation;
	// CONTROL vars
	private SendMessageTask sendMessageTask;
	private IntentFilter messageFilter;
	private GCMReceiver gcmMessageReceier;
	private String broadcastMessage;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_message);
		if (getIntent().hasExtra(Constants.FIELD_REQUEST_CODE)) {
			String requestCode = getIntent().getStringExtra(
					Constants.FIELD_REQUEST_CODE);
			if (Integer.parseInt(requestCode) == Constants.REQUEST_CODE_UPD) {
				// pull from DB all messages from this conversation
				// display messaged in the right order
			}
		}
		initUI();
		initReceiver();
	}
	private void initUI() {
		//tvMessage = (TextView) findViewById(R.id.tv_message);
		txtMessage = (EditText) findViewById(R.id.txtMsg);
		btnSend = (Button) findViewById(R.id.btnSend);
		btnSend.setOnClickListener(sendListener);

		initHeader();
		setHeaderTitle(getString(R.string.titleMessagesListActivity), Constants.TITLE_MESSAGESLIST_IMAGE_NUM);
	}

	private OnClickListener sendListener = new OnClickListener() {
		@Override
		public void onClick(View v) {

			if (TextUtils.isEmpty(txtMessage.getText())) {
				Toast.makeText(MessageActivity.this,
						"Please enter a message recipient.", Toast.LENGTH_SHORT)
						.show();
				return;
			}
			sendMessageToServer();
		}
	};
	
	private void initReceiver() {
		gcmMessageReceier = new GCMReceiver();
		messageFilter = new IntentFilter();
		messageFilter.addAction(Constants.ACTION_ON_NEW_MESSAGE);
	}

	// When an activity is re-created, the os generates an
	// onRestoreInstanceState()
	// event, passing it a bundle that contains any values that you may have put
	// in during onSaveInstanceState()
	// We can use this mechanism to re-display our last broadcast message.
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		broadcastMessage = savedInstanceState.getString("BroadcastMessage");
		tvMessage.setText(broadcastMessage);
	}

	@Override
	public void onResume() {
		super.onResume();
		registerReceiver(gcmMessageReceier, messageFilter);
		String msg = getIntent().getStringExtra(Constants.FIELD_MESSAGE);
		tvMessage.setText(msg);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(gcmMessageReceier);
	}

	// If the user changes the orientation of his phone, the current activity
	// is destroyed, and then re-created. This means that our broadcast message
	// will get wiped out during re-orientation.
	// So, we save the broadcast message during an onSaveInstanceState()
	// event, which is called prior to the destruction of the activity.
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		savedInstanceState.putString("BroadcastMessage", broadcastMessage);
	}

	public void sendMessageToServer() {
		txtMessage.setEnabled(false);
		sendMessageTask = new SendMessageTask(GlobalValue.registerId);
		sendMessageTask.execute();
	}

	class SendMessageTask extends AsyncTask<Void, Void, Integer> {
		Context context;
		private String regId;

		public SendMessageTask(String reg_id) {
			// TODO Auto-generated constructor stub
			this.regId = reg_id;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			showProgressDialog();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			int response = Constants.FAILED;
			try {
				String msg_id = CommonUtilities.getInstance(self).generateGUID(
						context);
				String wave_id = CommonUtilities.getInstance(self)
						.generateGUID(context);
				;
				// response = backendManager.sendMessage(txtMessage.getText()
				// .toString(), msg_id, wave_id, Constants.MESSAGE_ROOT,
				// regId, Constants.MSG_STATUS_ACTIVE);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return response;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			txtMessage.setEnabled(true);
			txtMessage.setText("");
			closeProgressDialog();
			tvMessage.setText(String.valueOf(result));
			Intent i = new Intent(self, ConversationActivity.class);
			self.startActivity(i);
		}
	}

	private class GCMReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			broadcastMessage = intent.getExtras().getString(
					Constants.FIELD_MESSAGE);
			if (broadcastMessage != null) {
				// display our received message
				tvMessage.setText(broadcastMessage);
			}
		}
	};

	private void reloadLanguage() {
		setHeaderTitle(getString(R.string.titleMessagesListActivity), Constants.TITLE_MESSAGESLIST_IMAGE_NUM);
		updateStatusTitle();
	}

}
